package org.xxpay.pay.channel.zy2pay;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.util.PayDigestUtil;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayNotify;
import org.xxpay.pay.util.MyHttp;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: pangxiaoyu
 * @date: 2021-01-25
 */
@Service
public class Zy2payPayNotifyService extends BasePayNotify {

    private static final MyLog _log = MyLog.getLog(Zy2payPayNotifyService.class);
    private static final String logPrefix = "【处理"+ Zy2payConfig.CHANNEL_NAME+"支付回调】";

    @Override
    public String getChannelName() {
        return Zy2payConfig.CHANNEL_NAME;
    }

    @Override
    public JSONObject doNotify(Object notifyData) {
        _log.info("====== 开始处理{}支付回调通知 ======", getChannelName());
        HttpServletRequest request = (HttpServletRequest) notifyData;
        JSONObject retObj = buildRetObj();
        Map<String, String> payContext = new HashMap();

        String respString = Zy2payConfig.RETURN_VALUE_ERROR;
        try {
            PayOrder payOrder = verifyPayParams(request, payContext);
            if( payOrder == null ) { //验证参数失败
                retObj.put(PayConstant.RESPONSE_RESULT, Zy2payConfig.RETURN_VALUE_ERROR);
                return retObj;
            }
            //订单已经支付完成
            if(payOrder.getStatus() == PayConstant.PAY_STATUS_SUCCESS || payOrder.getStatus() == PayConstant.PAY_STATUS_COMPLETE){
                retObj.put(PayConstant.RESPONSE_RESULT, Zy2payConfig.RETURN_VALUE_SUCCESS);
                return retObj;
            }
            //上游通知 状态
            String channelOrderNo = payContext.get("trade_no"); //上游订单号

            int updatePayOrderRows = commonService.payOrderService.updateStatus4Success(payOrder.getPayOrderId(), channelOrderNo);
            if (updatePayOrderRows != 1) {
                _log.error("{}更新支付状态失败,将payOrderId={},更新payStatus={}失败", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
                retObj.put(PayConstant.RESPONSE_RESULT, "处理订单失败");
                return retObj;
            }
            _log.error("{}更新支付状态成功,将payOrderId={},更新payStatus={}成功", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
            payOrder.setStatus(PayConstant.PAY_STATUS_SUCCESS);

            // 业务系统后端通知
            baseNotify4MchPay.doNotify(payOrder, true);
            _log.info("====== 完成处理{}支付回调通知 ======", getChannelName());
            respString = Zy2payConfig.RETURN_VALUE_SUCCESS;
        } catch (Exception e) {
            _log.error(e, logPrefix + "处理异常");
        }
        retObj.put(PayConstant.RESPONSE_RESULT, respString);
        return retObj;
    }

    /**
     * 验通知参数
     * @return
     */
    public PayOrder verifyPayParams(HttpServletRequest request, Map<String, String> payContext) {
        try{
            JSONObject paramObj = MyHttp.getParam(request);
            _log.info("{}获取请求数据:{}", logPrefix, paramObj);

            // 验证参数是否合法
            String memberid = paramObj.getString("memberid");         // 商户编号
            String orderid = paramObj.getString("orderid");           // 订单号
            String amount = paramObj.getString("amount");         // 订单金额
            String transactionId = paramObj.getString("transaction_id");         // 交易流水号
            String datetime = paramObj.getString("datetime");         // 交易时间
            String returncode = paramObj.getString("returncode");         //交易状态
            String attach = paramObj.getString("attach");         // 扩展返回 不参与签名
            String sign = paramObj.getString("sign");         // 签名

            _log.info("{}memberid={}, orderid={}, amount={}, transactionId={}, datetime={}, returncode={}, attach={}, sign={}" ,
                    logPrefix, memberid, orderid, amount, transactionId, datetime, returncode ,attach, sign);

            if(StringUtils.isAnyEmpty(orderid, memberid, amount, sign)){
                _log.error("{}orderid={}, memberid={}, amount={}, sign={}", logPrefix, orderid, memberid, amount, sign);
                return null;
            }

            // 验证状态
            if (!"00".equals(returncode)) {
                _log.error("状态错误 ,payOrderId={}, status={}", orderid, returncode);
                return null;
            }

            // 查询payOrder记录
            String payOrderId = orderid;
            PayOrder payOrder = commonService.payOrderService.findByPayOrderId(payOrderId);
            if (payOrder == null) {
                _log.error("Can't found payOrder form db. payOrderId={}, ", payOrderId);
                return null;
            }

            Zy2payConfig zy2payConfig = new Zy2payConfig(getPayParam(payOrder));
            // 验证签名
            Map<String, String> params = new HashMap<>();
            params.put("memberid", memberid);
            params.put("orderid", orderid);
            params.put("amount", amount);
            params.put("transaction_id", transactionId);
            params.put("datetime", datetime);
            params.put("returncode", returncode);

            String myselfSign = PayDigestUtil.getSign(params, zy2payConfig.getApiKey());

            if(!sign.equals(myselfSign)) {
                _log.error("验证签名失败. payOrderId={}, ", payOrderId);
                return null;
            }
            payContext.put("trade_no", transactionId);
            return payOrder;
        } catch (Exception e) {
            _log.error("验证响应数据异常", e);
        }
        return null;
    }

}
